package handlers

import (
	"InstantImage/tcpService"
	"InstantImage/util"
	"encoding/base64"
	"net/http"

	"github.com/gin-gonic/gin"
)

func getImageHandler(service *tcpService.TcpService) gin.HandlerFunc {
	return func(c *gin.Context) {

		dialGET, _ := service.GetPool.Get()
		defer service.GetPool.Put(dialGET)
		key := c.Param("key")
		val, err := util.Quary(dialGET, []byte(key))
		if err != nil {
			c.JSON(http.StatusBadGateway, gin.H{
				"message": "NotFind",
			})
		}
		msg := string(val)
		switch msg {
		case "NotFind":
			c.HTML(http.StatusNotFound, "404.html", gin.H{})
			return
		}
		imageData, _ := base64.StdEncoding.DecodeString(string(val))

		c.Header("Content-Type", "image/png")
		c.Writer.Write(imageData)
	}
}
